package com.example.juccode.juc02completableFuture.demo;

import java.util.concurrent.*;

/**
 * @author: zhongkui 1365693530@qq.com
 * @Date: 2025/2/10
 */
public class CompletableFutureUseDemo {

    public static void main(String[] args) throws Exception {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

//        CompletableFuture优点：
//            ● 异步任务结束时，会自动回调某个对象的方法
//            ● 主线程设置好回调后，不用关心异步任务的执行，异步任务之间可以顺序执行
//            ● 异步任务出错时，会自动回调某个对象的方法
        try {

            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "------开始执行");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {TimeUnit.MILLISECONDS.sleep(1000);} catch (Exception e) {e.printStackTrace();}
                System.out.println("1秒后出结果=" + result);

                if (result > 5)
                {
                    int i = 10/0;
                }
                return result;
            },threadPool).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("------计算完成--result+" + v);
                }
            }).exceptionally(e -> {
                System.out.println("------计算异常--" + e.getMessage());
                e.printStackTrace();
                return null;
            });

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

//        System.out.println(Thread.currentThread().getName() + "--线程，先去忙其他任务");
//        // 主线程不要立刻结束,否则CompletableFuture默认使用的线程池会立刻关闭,
//        try {TimeUnit.MILLISECONDS.sleep(2000);} catch (Exception e) {e.printStackTrace();}
//        System.out.println("结束");

    }

    public static void future1(String[] args) throws Exception {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "------开始执行");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("1秒后出结果=" + result);
            return result;
        });
        System.out.println(Thread.currentThread().getName() + "--线程，先去忙其他任务");

        System.out.println(completableFuture.get());
        threadPool.shutdown();
    }
}
